package cn.kailangtu.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import java.util.concurrent.LinkedBlockingQueue;

import cn.kailangtu.myapplication.databinding.ActivityMain2Binding;
import cn.kailangtu.serialport.CanBaudrate;
import cn.kailangtu.serialport.CommonUtils;
import cn.kailangtu.serialport.ReceiveData;
import cn.kailangtu.serialport.ReceiveMsgListener;
import cn.kailangtu.serialport.SerialPortApi485;
import cn.kailangtu.serialportv2.DataVersion2;
import cn.kailangtu.serialportv2.ReceiveMsgListenerV2;

public class MainActivity2 extends AppCompatActivity {

    private String TAG = "MainActivity";
    private ActivityMain2Binding binding;
    private AppBarConfiguration appBarConfiguration;

    private LinkedBlockingQueue<byte[]> reportMsgQueue = null;

    SerialPortApi485 serialPortApi =new SerialPortApi485();

    String selectedCanBaudrate = "200kbps";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        reportMsgQueue= new LinkedBlockingQueue<>();
        binding = ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //EventBus.getDefault().register(this);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.options_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.etCANBaudrate.setAdapter(adapter);

        binding.etCANBaudrate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 选择项被选中时的回调
                selectedCanBaudrate = parent.getItemAtPosition(position).toString();
                // 处理选中的选项
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 无选项被选中时的回调
            }
        });

        binding.btnSend.setEnabled(false);

        binding.btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开串口
                String portName = binding.etPortName.getText().toString();
                int baudrate =  Integer.parseInt(binding.etBaudrate.getText().toString());
                //serialPortApi.openSerialPort(ttyHSL0, 115200, 0, new ReceiveMsgListener()
                if(serialPortApi.openSerialPort(portName, baudrate, 0)){
                    binding.btnSend.setEnabled(true);
                    appendMsg("打开串口成功："+portName+","+baudrate);
                }
                else
                {
                    binding.btnSend.setEnabled(false);
                    appendMsg("打开串口失败："+portName+","+baudrate);
                }
            }
        });

        try {
            binding.btnSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("SERIALAAAAA","1");
                    String add = binding.etAddress.getText().toString();
                    String data = binding.etData.getText().toString();
                    //ID
                    byte[] addByte = CommonUtils.hexStringToByteArray(add);
                    //数据
                    byte[] dataByte = CommonUtils.hexStringToByteArray(data);
                    //发送数据
                    // serialPortApi.send(addByte,dataByte,binding.cbFrameType.isChecked());
                  //  serialPortApi.sendBytes(CommonUtils.hexStringToByteArray("010300010001D5CA"));
                    Log.d("SERIALAAAAA","2");
                }
            });

        } catch (NumberFormatException e) {

        }

        binding.btnAtBaudrate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int mode = 5;
                if(binding.rbMode1.isChecked())
                {
                    mode =1;
                }
                else if(binding.rbMode2.isChecked())
                {
                    mode =2;
                }
                else if(binding.rbMode3.isChecked())
                {
                    mode =3;
                }
                else if(binding.rbMode4.isChecked())
                {
                    mode =4;
                }
                else  if(binding.rbMode5.isChecked())
                {
                    mode =5;
                }

                String localBaudrate = binding.etLocalBaudrate.getText().toString();
                String canBaudrate = CanBaudrate.getCanBaudrateString(selectedCanBaudrate);

                Log.d(TAG,localBaudrate);
                Log.d(TAG,canBaudrate);
              //  serialPortApi.setBaudrate(localBaudrate,canBaudrate,mode);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }



    @Override
    protected void onResume() {
        super.onResume();

        //mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //用户不在当前页面时，停止监听
        //mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
    }

    private void showMsg(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                binding.tvMsg.setText(msg);
            }
        });
    }

    private void appendMsg(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if(binding.tvMsg.getLineCount() > 50)
                {
                    binding.tvMsg.setText("");
                }


                binding.tvMsg.append(msg + "\r\n");
            }
        });
    }



    @Override
    protected void onDestroy() {
        try{
            //EventBus.getDefault().unregister(this);
            serialPortApi.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();;
        }
        super.onDestroy();
    }

    private class ProcessThread extends  Thread{
        @Override
        public void run() {
            super.run();

            while (!isInterrupted()) {

                try {
                    byte[] currentCmd = reportMsgQueue.take();


                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }

        }
    }
}